#include "log.hpp"
void slaver()
{
    //创建日志
    Log log;
    cout<<"子进程准备读取"<<endl;
     while (true)
    {
        char buffer[1024] = {0};
        int n = read(0, buffer, sizeof(buffer));
        if(n > 0)
        {
            cout<<"子进程server已经读到:"<<buffer<<" 立刻执行"<<endl;
        }
        else
        {
            log.logmessage(Debug,"子进程读取结束 退出信息:%s 退出码:%d",strerror(errno),errno);
            break;
        }
    }
}
void InitChannels(vector<channel>& channels)
{
    vector<int> ProcessPid;
    for(int i = 0; i < PRONUM; i++)
    {
        //创建匿名管道
        int fd[2]={0};
        int ret = pipe(fd);
        int id = fork();
        if(id < 0)
        {
            perror("fork");
            exit(FORK_ERR);
        }
        else if(id == 0)//子进程读
        {
            for(auto e : ProcessPid)
                close(e);
            close(fd[1]);
            dup2(fd[0],0);
            slaver();
            exit(0);
        }
        //父进程负责写
        close(fd[0]);
        string proname = "process->";
        proname += to_string(i);
        channels.push_back(channel(fd[1],id,proname));
        ProcessPid.push_back(fd[1]);
    }
}
void DebugPrint(const vector<channel>& channels)
{
   for (auto& e : channels)
   {
       cout << "fd: " << e._fd << " " << "_pid: " << e._pid << " " << "proname: " << e._proname << " ppid: " << getppid() << endl;
   }
}
void Ctrlprocess(const vector<channel>& channels)
{
    Init it;
    Log log;
    int fd = open(FILENAME,O_CREAT|O_APPEND|O_RDONLY,0666);
    int which = 0;
    //读取信息
     while (true)
    {
        char buffer[1024] = {0};
        int n = read(fd, buffer, sizeof(buffer));
        if(n > 0)
        {
            cout<<"父进程server已经读到:"<<buffer<<" 正在让子进程处理"<<endl;
            //轮转挑选子进程
            int fd = channels[which++]._fd;
            write(fd,buffer,sizeof(buffer));
            which%=channels.size();
        }
        else
        {
            log.logmessage(Debug,"父进程读取结束 退出信息:%s 退出码:%d",strerror(errno),errno);
            break;
        }
    }
}
void QuitProcess(const vector<channel>& channels)
{
    for(auto e : channels)
    {
        close(e._fd);
        int status = 0;
        waitpid(e._pid,&status,0);
    }
}
int main()
{
    //父进程拿到其它进程的信息，并写给子进程去处理
    // 1 初始化channels
    vector<channel> channels;
    InitChannels(channels);
    // DebugPrint(channels);//父进程执行完后退出，子进程认为写端关闭，也退出了
    //2 控制子进程
    Ctrlprocess(channels);
    //3 清理文件描述符
    QuitProcess(channels);
    return 0;
}